package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.List;

/**
 * 自定义解码器，了解handle 调用链
 */
@Slf4j
public class ByteCodecChainCase {
    private static final  int PORT =6668;
    
    @Test
    public void chainServer(){
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChainServerInitializer());
            log.error("服务器 准备完成");
            ChannelFuture cf = serverBootstrap.bind(PORT).sync();

            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    
    
    @Test void chainClient(){
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 出站编码器
                            pipeline.addLast(new MyLongToByteEncoder());
                            // 自定义业务处理器
                            pipeline.addLast(new MyClientHandle());
                            
                        }
                    });
            log.error("客户端 ok。。。");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", PORT).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
    
    private static class MyLongToByteEncoder extends MessageToByteEncoder<Long>{

        @Override
        protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
            log.error("MyLongToByteEncoder 被调用,msg:{}",msg);
            out.writeLong(msg);
            
        }
    }
    private static class MyClientHandle extends SimpleChannelInboundHandler<Long>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
            
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            log.error("MyClientHandle 被调用");
            ctx.writeAndFlush(123456L);
            // todo 思考 若是直接传递的是字符串，将会怎么样
            // 看 io.netty.handler.codec.MessageToByteEncoder.write 方法
            // 结论：若是发的数据类型和接受的数据类型，不一致，将会导致发送的时候，编码器跳过
            // ctx.writeAndFlush(Unpooled.copiedBuffer("abcdefghijklmnop", StandardCharsets.UTF_8));
        }
    }
    
    private static class ChainServerInitializer extends ChannelInitializer<SocketChannel>{

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new MyByteToLongDecode());
            pipeline.addLast(new MyServerChainHandler());
        }
    }
    private static class MyByteToLongDecode extends ByteToMessageDecoder {
        


        /**
         * @param ctx 上下文
         * @param in 入站 buf
         * @param out list集合
         * @throws Exception
         */
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            log.error("MyByteToLong 被调用");
            if (in.readableBytes() >=8){
                out.add(in.readLong());
            }
        }
    }
    private static class MyServerChainHandler extends SimpleChannelInboundHandler<Long>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
         log.error("接受到客户端信息:{}",msg);
            
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();;
            ctx.close();
        }
    }
}
